package 剑指Offer._1120;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/8 14:20
 * 矩阵中的路径
 * 算法：回溯
 */
public class _12 {

    public boolean exist(char[][] board, String word) {
        if ("".equals(word)) return true;
        int m = board.length, n = board[0].length;
        if (m * n < word.length()) return false;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(board, word, i, j, 0, visited)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, String word, int i, int j, int start, boolean[][] visited) {
        if (start == word.length() - 1) return true;
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length ||
        visited[i][j] || board[i][j] != word.charAt(start)) return false;
        visited[i][j] = true;
        boolean ans = dfs(board, word, i - 1, j, start + 1, visited)
                || dfs(board, word, i, j - 1, start + 1, visited)
                || dfs(board, word, i, j + 1, start + 1, visited)
                || dfs(board, word, i + 1, j, start + 1, visited);
        visited[i][j] = false;
        return ans;
    }

}
